from django import forms
from web import models
from web.models import UserInfo
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.conf import settings
class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号',validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9|])\d{9}$','手机号格式错误'),])
    password = forms.CharField(label='密码',widget=forms.PasswordInput())
    comfirm_password = forms.CharField(label='重复密码',widget=forms.PasswordInput(attrs={'class':'from-cont'}))
    code = forms.CharField(label='验证码')
    class Meta:
        model = models.UserInfo
        fields = "__all__"
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' %(field.label)


    def clean(self):
        pwd = self.cleaned_data.get("password")
        re_pwd = self.cleaned_data.get("comfirm_password")
        if pwd and re_pwd:
            if pwd == re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("两次密码不一致！")
        else:
            return self.cleaned_data

    def clean_user(self):
        val=self.cleaned_data.get("username")
        user=UserInfo.objects.filter(username=val).first()
        if not user:
            return val

        else:
            raise ValidationError("该用户已经注册！")

class SendSmsForm(forms.Form):

    mobile_phone = forms.CharField(label='手机号',validators=[[RegexValidator(r'^(1[3|4|5|6|7|8|9|])\d{9}$','手机号格式错误'),]])

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request
    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data["mobile_phone"]

        #判断短信模板是否有问题（判断是否是爬虫）
        tpl = self.request.GET.get
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            raise ValidationError("短信模板错误")
        #判断数据库是否有手机号
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).existe()
        if exists:
            raise ValidationError("手机号已存在")




        return mobile_phone